//
//  SHChooseAlbumTool.m
//  Tradeaider
//
//  Created by 王方伟 on 2017/5/18.
//  Copyright © 2017年 Shinyhub. All rights reserved.
//

#import "SHChooseAlbumTool.h"
#import "TZImagePickerController.h"
#import "TZImageManager.h"
#import "SHAlertAction.h"
#import <CoreMotion/CoreMotion.h>

@interface SHChooseAlbumTool ()
@property (assign, nonatomic) BOOL isHidden;
@end

@implementation SHChooseAlbumTool
static NSString * const SHALBUMPHOTONAME = @"Tradeaider";
+ (instancetype)sharedChooseAlbum{
    static SHChooseAlbumTool *sharedClass;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedClass = [[SHChooseAlbumTool alloc] init];
    });
    return sharedClass;
}


#pragma mark 保存图片到相册
- (void)saveImageToAlbum:(UIImage *)image completion:(void (^)(NSError *error))completion{
    dispatch_async(dispatch_get_main_queue(), ^{
        NSError *error = nil;
        
        // 保存相片到相机胶卷
        __block PHObjectPlaceholder *createdAsset = nil;
        [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
            createdAsset = [PHAssetCreationRequest creationRequestForAssetFromImage:image].placeholderForCreatedAsset;
        } error:&error];
        
        if (error) {
            NSLog(@"保存失败：%@", error);
            return;
        }
        
        // 拿到自定义的相册对象
        PHAssetCollection *collection = [self collection];
        if (collection == nil) return;
        
        [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
            [[PHAssetCollectionChangeRequest changeRequestForAssetCollection:collection] insertAssets:@[createdAsset] atIndexes:[NSIndexSet indexSetWithIndex:0]];
        } error:&error];
        if (completion) {
            completion(error);
        }
        if (error) {
            NSLog(@"保存失败：%@", error);
        } else {
            if (!_isHidden) {
                [SVProgressHUD showSuccess:@"图片已保存"];
                _isHidden = FALSE;
            }
            
        }
    });
}


- (PHAssetCollection *)collection{
    // 先从已存在相册中找到自定义相册对象
    PHFetchResult<PHAssetCollection *> *collectionResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    for (PHAssetCollection *collection in collectionResult) {
        if ([collection.localizedTitle isEqualToString:SHALBUMPHOTONAME]) {
            return collection;
        }
    }
    
    // 新建自定义相册
    __block NSString *collectionId = nil;
    NSError *error = nil;
    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
        collectionId = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:SHALBUMPHOTONAME].placeholderForCreatedAssetCollection.localIdentifier;
    } error:&error];
    
    if (error) {
        SHLog(@"获取相册【%@】失败", SHALBUMPHOTONAME);
        return nil;
    }
    
    return [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[collectionId] options:nil].lastObject;
}


#pragma mark 长按保存
- (void)longPanSaveImageToAlbum:(UIImage *)image{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    __weak typeof(self) weakSelf = self;
    SHAlertAction *actionA = [SHAlertAction actionWithTitle:@"保存图片" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf saveImageToAlbum:image completion:nil];
    }];
    
    SHAlertAction *actionB = [SHAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertVC addAction:actionA];
    [alertVC addAction:actionB];
    [DCURLRouter presentViewController:alertVC animated:YES completion:nil];
}

//回调方法
- (void)image:(UIImage *)image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo{
    if(error != NULL){
        SHLog(@"保存图片失败");
    }else{
        if (!_isHidden) {
            [SVProgressHUD showSuccess:@"图片已保存"];
            _isHidden = FALSE;
        }
    }
}

@end
